﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using System.IO.IsolatedStorage;

namespace ByrForum
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            try
            {
                //读取文件
                IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();

                //创建一个新的StreamReader
                StreamReader fileReader = null;
                fileReader = new StreamReader(new IsolatedStorageFileStream("userinfo.txt", FileMode.Open, fileStorage));
                //读取内容
                textBoxUsername.Text = fileReader.ReadLine();
                passwordBoxPassword.Password = fileReader.ReadLine();
                fileReader.Close();
            }
            catch
            {

            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.buttonLogin.IsEnabled = true;
        }
        private void buttonLogin_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxUsername.Text == "" || passwordBoxPassword.Password == "")
            {
                MessageBox.Show("密码或用户名不能为空！");
                return;
            }
            App.MyInfo.password = passwordBoxPassword.Password;
            App.MyInfo.id= textBoxUsername.Text;

            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            StreamWriter fileWriter = null;
            fileWriter = new StreamWriter(new IsolatedStorageFileStream("userinfo.txt", FileMode.Create, store));
            //向文件中写出内容
            fileWriter.WriteLine(textBoxUsername.Text);
            fileWriter.WriteLine(passwordBoxPassword.Password);
            fileWriter.Close();



            String myRequestUrl = ByrApi.apiUrl + "/user/login" + ByrApi.Encode + ByrApi.appkey;/*ByrApi.Encode*/
            
            HttpUtil.HttpGet(myRequestUrl, HttpWebRequset_Callback);
            progressBarWait.Visibility = Visibility.Visible;
            buttonLogin.IsEnabled = false;
        }
        private void HttpWebRequset_Callback(IAsyncResult asynchronousResult)
        {
            
            
            try
            {
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                Debug.WriteLine(result);
                XDocument doc = XDocument.Parse(result);
                if (((XElement)doc.FirstNode).Name != "error")
                {
                    foreach (XElement item in doc.Descendants("user").Nodes())
                    {
                        switch (item.Name.ToString())
                        {
                            case "id":
                                App.MyInfo.id = item.Value;
                                break;
                            case "user_name":
                                App.MyInfo.user_name = item.Value;

                                break;
                            case "face_url":
                                App.MyInfo.face_url = item.Value;
                                break;
                            case "gender":
                                App.MyInfo.gender = item.Value;
                                break;
                            case "astro":
                                App.MyInfo.astro = item.Value;
                                break;
                            case "life":
                                App.MyInfo.life = item.Value;
                                break;
                            case "post_count":
                                App.MyInfo.post_count = item.Value;
                                break;
                            case "score":
                                App.MyInfo.score = item.Value;
                                break;
                            default:
                                break;

                        }
                    }
                    Debug.WriteLine(App.MyInfo.user_name);

                    this.Dispatcher.BeginInvoke(
                        () => {
                            this.progressBarWait.Visibility = Visibility.Collapsed;
                            this.NavigationService.Navigate(new Uri("/PanoramaMainPage.xaml",UriKind.Relative));
                        }
                        );
                }
                else
                {
                    foreach (XElement item in doc.Descendants("error").Nodes())
                    {
                        if (item.Name == "msg")
                        {
                            this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    MessageBox.Show(item.Value);
                                    this.progressBarWait.Visibility = Visibility.Collapsed;
                                    this.buttonLogin.IsEnabled = true;
                                }
                                );
                            


                            return;
                        }
                    }
                }
                this.Dispatcher.BeginInvoke(
                    () => {
                        progressBarWait.Visibility = Visibility.Collapsed;
                    }
                    );

            }
            catch
            {
                Debug.WriteLine("get callback failed");
                this.Dispatcher.BeginInvoke(
                    () => {
                        MessageBox.Show("无法连接到网络！");
                        progressBarWait.Visibility = Visibility.Collapsed;
                        this.buttonLogin.IsEnabled = true;
                    }
                    );
            }
            finally {
            
            }
        }
    }
}